import React, { useEffect, useState } from 'react'
import './index.less'
import Dragger from 'antd/lib/upload/Dragger';
import { Button, Checkbox, message, Table, Tag, type TableProps, Modal } from 'antd';
import request from '../../api';
import type { UploadProps } from 'antd';
import { formatDate } from '../../utils/moment';


interface DataType {
  key?: any;
  upload_time?: string;
  original_filename?: string;
  exec_status?: string;
  exec_mae?: string;
  duration?: string;
  select_result?: boolean;
  unique_filename?: string;
  running_time?: string;
  error_msg?: string;
}

const CodeUpload = () => {
    let [remainCount, setRemainCount] = useState(3);
    const [data, setData] = useState<DataType[]>([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [errorMsg, setErrorMsg] = useState(false);
  
    useEffect(()=>{
      getRemainCount()
      getUploadHistory()
    },[])

    const columns: TableProps<DataType>['columns'] = [
      {
        title: '',
        dataIndex: 'count',
        key:  'count',
        render:(_,__,index)=><span>{index+1}</span>
      },
      {
        title: '上传时间',
        dataIndex: 'upload_time',
        align: 'center',
        key:  'upload_time',
        render: (text) => formatDate(text)
      },
      {
        title: '文件名',
        dataIndex: 'original_filename',
        align: 'center',
        key: 'original_filename',
      },
      {
        title: '状态',
        dataIndex: 'exec_status',
        align: 'center',
        key: 'exec_status',
        render: (_, record) => (
          getTag(record)
        )
      },
      {
        title: 'TWMAE',
        dataIndex: 'wmae',
        align: 'center',
        key: 'wmae',
        render: (text) => parseFloat(text).toFixed(4)
      },
      {
        title: 'MAE',
        dataIndex: 'exec_mae',
        align: 'center',
        key: 'exec_mae',
        // render: (text) => parseFloat(text).toFixed(4)
        render: (_, record) => (
          getMae(record)
        )
      },
      {
        title: '运行时长(s)',
        dataIndex: 'running_time',
        align: 'center',
        key: 'running_time',
        render: (_, record) => (
          getRunningTime(record)
        )
      },
      {
        title: '详情',
        dataIndex: 'error_msg_button',
        align: 'center',
        key: 'error_msg_button',
        render: (_, record) => {
          if(record.exec_status == "3"){
            return (
              <Button color="danger" type='link' onClick={() => showModal(record)} size='small'>失败原因</Button>
            )
          }
        }
      },
      {
        title: '选中为最终结果',
        dataIndex: 'key',
        align: 'center',
        key: 'select_result',
        render: (_, record) => (
          <Checkbox
            disabled={record.exec_status != '1'}
            checked={record.select_result? true : false}
            onChange={() => onChange(record)}
          ></Checkbox>
        )
      },
    ];

  const showModal = (record: any) => {
    setErrorMsg(record.error_msg)
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

    const getTag = (record: DataType) => {
      switch(String(record.exec_status)) {
        case '-1':
          return (
            <Tag color="error">解析错误</Tag>
          )
        case '0':
          return (
            <Tag color="default">排队中</Tag>
          )
        case '1':
          return (
            <Tag color="success">运行成功</Tag>
          )
        case '2':
          return (
            <Tag color="error">运行超时</Tag>
          )
        case '3':
          return (
            <div>
              <Tag color="error">运行失败</Tag>
            </div>
          )
        case '4':
          return (
            <Tag color="processing">运行中</Tag>
          )
      }
    }

    const getMae = (record: DataType) => {
      if(String(record.exec_status) != '1'){
        return "/"
      }else{
        return parseFloat(String(record.exec_mae)).toFixed(4)
      }
    }

    const getRunningTime = (record: DataType) => {
      if(String(record.exec_status) != '1'){
        return "/"
      }else{
        return record.running_time
      }
    }

    const onChange = (record: DataType) => {
      if (record.select_result) {
        // 如果当前选中的就是点击的行，阻止操作
        return;
      }
      request.selectResult({"unique_filename": record.unique_filename}).then(res => {
        if (res?.status == 200) {
          message.success("选中成功")
        }
      })
      const updatedData = data.map(item => ({
        ...item,
        select_result: item.key === record.key ? !item.select_result : false,
      }));
      setData(updatedData);
    };

    const getRemainCount = () =>{
      request.getRemainCount().then(res => {
          if (res.status == 200) {
              setRemainCount(res.data.data.remaining_count)
          }
      })
    }

    const getUploadHistory = () =>{
      request.getUploadHistory().then(res => {
          if (res.status == 200) {
              message.success(res.data.msg)
              const jsonArray = res.data.data.map((item, index) => {
                  const parsedItem = JSON.parse(item);
                  return {
                    ...parsedItem,
                    key: index  // 使用行号作为唯一 key
                  };
              })
              setData(jsonArray.reverse())
          }
      })
    }

    const get_user_id = () => {
      const UserInfo = localStorage.getItem('gamer-info')

      if (UserInfo){
          const parsedUserInfo = JSON.parse(UserInfo);
          return parsedUserInfo.userInfo.user_id;
      }
    }

    // const props: UploadProps = {
    //   name: 'file',
    //   multiple: false,
    //   action: 'http://localhost:4567/api/upload',
    //   headers: {
    //     'Authorization': 'Bearer your-token',
    //       'Cookie': 'your_cookie_name=your_cookie_value' // 直接添加cookie
    //   },
    //   onChange(info) {
    //     const { status, response } = info.file;
    //     if (status !== 'uploading') {
    //       console.log(info.file, info.fileList);
    //     }
    //     if (status === 'done') {
    //       console.log(response);
    //       if(response.ret == -1){
    //         message.error(response.msg)
    //       }
    //       if(response.ret == 0){
    //         message.success(response.msg)
    //       }
    //       getRemainCount()
    //       setTimeout(() => {
    //           getUploadHistory()
    //       }, 3500)
          
    //     } else if (status === 'error') {
    //       message.error(`${info.file.name} file upload failed.`);
    //     }
    //   },
    //   onDrop(e) {
    //     console.log('Dropped files', e.dataTransfer.files);
    //   },
    // };

  const props: UploadProps = {
    showUploadList: false,
    beforeUpload: (file) => {
      // 检查文件大小
      const MAX_SIZE = 10 * 1024 * 1024; // 10MB
      if (file.size > MAX_SIZE) {
        message.error('文件大小不能超过 10MB');
        return false; // 阻止上传
      }
      // 自定义上传逻辑，例如使用 fetch 或 axios
      const formData = new FormData();
      formData.append('file', file);

      const currentUrl = window.location.href;
      const url = new URL(currentUrl);

      // 构建包括端口号的完整地址
      const completeUrl = `${url.protocol}//${url.hostname}:${url.port}/`; // 注意最后的斜杠
      console.log(completeUrl); // 输出: http://192.168.199.16:4567/


      fetch(completeUrl + 'api/upload', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer your-token',
          // 不在这里手动设置 Cookie
        },
        body: formData,
        credentials: 'include' // 确保发送 Cookie
      })
      .then(response => response.json())
      .then(response => {
        if (response.ret === -1) {
          message.error(response.msg);
        } else {
          message.success(response.msg);
          getRemainCount()
          setTimeout(() => {
              getUploadHistory()
          }, 3500)
        }
      })
      .catch(error => {
        message.error(`${file.name} file upload failed.`);
      });

      // 返回 false 以阻止默认上传行为
      return false;
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    }
  };

    return (
      <>
        <div>
          <div className="title">代码上传</div>
          <div className="dragger-box">
              <Dragger className='dragger' {...props}>
                  <p className="ant-upload-text">拖拽文件至此上传 或 点击打开本地位置</p>
                  <p style={{'color': 'gray'}}> .zip 限制10M以内</p>
              </Dragger>
          </div>
          <div className='hint'>     
              <span>提示：您今日运行次数剩余</span>
              <span className='bule-font'> {remainCount} </span>
              <span>次。请务必于</span>
              <span className='bule-font'> 2024-12-18 </span>
              <span>前完成代码上传及最终结果选择。</span>
          </div>
        </div>
        <div style={{display:'flex',justifyContent:'space-between',marginTop:20}}>
          <div className="title">我的历史上传</div>
          <Button type="primary" onClick={getUploadHistory}>刷新</Button>
        </div>
        <Table 
          columns={columns} 
          dataSource={data} 
          bordered 
          size='small' 
          // pagination={{showTotal: (total) => `共 ${total} 条记录`}}
        />
        <Modal open={isModalOpen} onCancel={handleCancel} footer={null}>
          <div
            dangerouslySetInnerHTML={{__html: errorMsg}}
          ></div>
        </Modal>
      </>
    )
}

export default CodeUpload
